package com.chen.util;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;


/**
 * filter过滤器像栈一样，先进后出
 */
public class MyFilter2 implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("init---filter2");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String uri = request.getRequestURI();//请求地址
        System.out.println("doFilter2---开始执行,uri="+uri);
        if (uri.endsWith("show.jsp")) {
            Object username = request.getSession().getAttribute("username");
            if (username == null) {
                request.getRequestDispatcher("index.jsp").forward(request, response);
                return;
            }
        }
        //调取对应的servlet,或者调取下一个filter
        filterChain.doFilter(servletRequest, servletResponse);
        System.out.println("doFilter2---结束执行");
    }

    @Override
    public void destroy() {
        System.out.println("destroy---filter2");
    }
}
